<?php


namespace App\Services;

class OAuthService extends BaseService
{
    /**
     * 解析state参数
     * 1.url%3Dhttps%253A%252F%252Fwww.tingjunapp.com%252F__tourist_id%3D00KFOPUWQRW5QA0I7EUAN577
     * 2.url%3Dhttps%253A%252F%252Fwww.tingjunapp.com%252F__tourist_id%3D00KFOPUWQRW5QA0I7EUAN577__where%3Dr__user_id%3D00K6R8O34PTZSXNP7GFU0GQ7
     * @param $state
     * @return array
     */
    public function parseState($state): array
    {
        $stateParams = [];
        $newState = '';
        $stateInfoArr = explode('__', $state);
        foreach ($stateInfoArr as $item) {
            $index = substr($item, 0, strpos($item, '='));
            $value = substr($item, strpos($item, '=') + 1);
            $stateParams[$index] = $value;
            if ($index !== 'where' && $index !== 'now' && $index !== 'login_method') {
                if ($index == 'url') {
                    $urlInfo = parse_url($value);
                    $value = $urlInfo['scheme'] . '://' . $urlInfo['host'];
                }
                $newState .= $index . '=' . $value . '__';
            }
        }

        return [
            'stateParams' => array_filter($stateParams),
            'newState' => substr($newState, 0, -2),
        ];
    }
}
